package org.tang.stock;

import java.util.ArrayList;
import java.util.List;
//http://www.gupang.com/201006/0605202R010.html
public class KDJ {
	// REFLINE: 0, 20, 50, 80, 100;
	// RSV:=(CLOSE-LLV(LOW,N))/(HHV(HIGH,N)-LLV(LOW,N))*100;
	// K:SMA(RSV,M1,1);
	// D:SMA(K,M2,1);
	// J:3*K-2*D;
	private List<Stock> stocks;
	private Entity kdjs[];
	private int n = 9;
	private int m1 = 3;
	private int m2 = 3;

	
	public Entity[] getKdjs() {
		return kdjs;
	}
	public KDJ(List<Stock> stocks) {
		this(stocks, 9, 3, 3);
	}
	public KDJ(List<Stock> stocks,int n,int m1,int m2) {
		this.n = n;
		this.m1 = m1;
		this.m2 = m2;
		this.stocks = stocks;
		kdjs = new KDJ.Entity[stocks.size()];
		parseKDJ();
	}

	private double getRSV(int day) {
		int high = 0;
		int low = Integer.MAX_VALUE;
		for (int i = 0; i < n && (i + day) < stocks.size(); i++) {
			if (stocks.get(i + day).getHightPrice() > high)
				high = stocks.get(i + day).getHightPrice();
			if (stocks.get(i + day).getLowPrice() < low)
				low = stocks.get(i + day).getLowPrice();
		}
		if (day == (stocks.size() - 2)) 
			System.out.println("high = " + high + ", low = " + low +", close = " + stocks.get(day).getClosePrice()
					+", test = " +(stocks.get(day).getClosePrice() - low) * 100.0 / (high - low)
			);
		return (stocks.get(day).getClosePrice() - low) * 100.0 / (high - low);
	}

	private void parseKDJ() {
		for (int i = stocks.size() - 1; i >= 0; i--) {
			if (i == (stocks.size() - 1)) {
				kdjs[i]= new Entity(0.0, 0.0, 0.0);
			}else{
				Entity entity = new Entity();
				entity.k = getRSV(i)/m1 + kdjs[i+1].k*(m1-1)/m1;
				entity.d = entity.k/m2 + kdjs[i+1].d*(m2-1)/m2;
				entity.j = entity.k*3 - 2*entity.d;
				kdjs[i] = entity;
			}
		}
	}

	public static class Entity {
		public double k;
		public double d;
		public double j;

		Entity() {

		}

		Entity(double k,double d,double j) {
			this.k = k;
			this.d = d;
			this.j = j;
		}
		@Override
		public String toString() {
			
			return "k = " + k +", d = " +d + ",j = " + j;
		}
	}

}
